package com.yeshine.opendata.controller.front;

import com.yeshine.opendata.core.AppException;
import com.yeshine.opendata.entity.SysDictionary;
import com.yeshine.opendata.entity.User;
import com.yeshine.opendata.service.IUserService;
import com.yeshine.opendata.utils.*;
import com.yeshine.opendata.utils.mail.SimpleMailSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * Created by taohj on 2014/6/29.
 */

@Controller
@RequestMapping("/front/user")
public class UserController extends AbstractFrontControllerBase {


    @Autowired
    private IUserService service;


    /*
    * 注册
    * */
    @RequestMapping(value = "registerV")
    public String registerView() {
        return super.getPagePath("user/register");
    }


    /*
    * 注册
    * */
    @RequestMapping(value = "register")
    public String register(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password,
            @RequestParam(value = "repassword", required = true) String repassword,
            @RequestParam(value = "email", required = true) String email
    ) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        JsonResult result = verification(username, email);
        if (!result.isSuccess()) {
            getRequest().setAttribute("message",result.getMessage());
            return "forward:"+getPagePath("user/registerV");
        }
        if (service.create(user).isSuccess()) {
            String url = super.getBasePath() + "/front/user/activation?id=" + user.getId() + "&uid=" + MD5Util.MD5Code(user.getId() + username + email);
            SimpleMailSender.send("注册成功", "<p>请访问<a href='" + url + "'>这里</a>以激活你的账号<p>如果没有相应，请用浏览器访问 " + url + "", email);
            return setMessage("注册成功", "恭喜您，注册成功，请到您的邮箱激活该账号,然后<a href='/front/user/loginV'>登陆</a>");
        } else {
            throw new AppException("用户注册失败");
        }
    }




    /**
     * 注册验证
     * */
    @ResponseBody
    @RequestMapping(value = "registerVerification",method = RequestMethod.POST)
    public String registerVerification(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "email", required = false) String email
    ) {
        return verification(username, email).toString();
    }



    /**
     * 验证用户名 邮件  手机号码 是否已存在
     * */
    private JsonResult verification(String username, String email) {
        if (StringUtils.hasLength(username)) {
            User user = new User();
            user.setUsername(username);
            List<User> users = service.getList(user).getList();
            System.out.println(users.size());
            if (users != null && users.size() > 0) {
                return getFailureJsonResult("账号已存在！");
            }

        }

        if (StringUtils.hasLength(email)) {
            User user = new User();
            user.setEmail(email);
            List<User> users = service.getList(user).getList();
            System.out.println(users.size());
            if (users != null && users.size() > 0) {
                return getFailureJsonResult("邮箱已存在！");
            }
        }



        return getSuccessJsonResult("");
    }



    /**
     * 邮箱账号激活
     * */
    @RequestMapping("activation")
    public String activation(@RequestParam("id") Integer id,
                             @RequestParam("uid") String uid) {
        if (service.activation(id, uid).isSuccess()) {
            return setRequestForwordAttr("账号激活成功", "账号激活成功,3秒后跳转到登陆页", "/front/user/loginV");
        } else {
            return setMessage("激活失败", "账号激活失败，请联系管理员");
        }
    }



    /**
     * 登陆页面
     * */
    @RequestMapping(value = "loginV")
    public String loginView() {
        return "front/user/login";
    }


    /**
     * 登陆
     * */
    @RequestMapping(value = "login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("validateNumber") String validateNumber) {

        System.out.println(getRequest().getParameterMap());

        String serverValidateNumber= CookiesUtil.getValue("validateNumber",getRequest());

        /*if (!(serverValidateNumber+"").equalsIgnoreCase(validateNumber)){
            setRequestAttr("loginMsg","验证码不正确");
            return "forward:"+getPagePath("user/loginV");
        }*/

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        Result<User> result = service.login(user);

        if (!result.isSuccess()) {
            setRequestAttr("message", result.getMessage());
            setRequestAttr("username", username);
            setRequestAttr("loginMsg",result.getMessage());
            return "forward:"+getPagePath("user/loginV");
        }
        setSessionAttr("user", result.getTarget());

        return "redirect:/";
    }




    /**
     * 登出
     * */
    @RequestMapping("logOut")
    public String loginOut() {
        setSessionAttr("user", null);
        return "redirect:/front/user/loginV";
    }




    /**
     * 修改页面
     * */
    @RequestMapping(value = "modifyV",method = RequestMethod.GET)
    public  String modifyView(
    ){
        setRequestAttr("user",getSession().getAttribute("user"));
        return getPagePath("user/modify");
    }


    /**
     * 修改
     * */
    @RequestMapping(value = "modify",method = RequestMethod.POST)
    public String modify(
            @RequestParam(value = "id",required = false) Integer id,
            @RequestParam(value = "telephone",required = false) String telephone,
            @RequestParam(value = "realname",required = false) String realname,
            @RequestParam(value = "sex",required = false) Integer sex,
            @RequestParam(value = "birthday",required = false) String birthday,
            @RequestParam(value = "QQ",required = false) String QQ,
            @RequestParam(value = "headImage",required = false)MultipartFile headImage,
            @RequestParam(value = "description",required = false) String description
    )
    {


        User user=service.getById(id).getTarget();

        user.setTelephone(telephone);
        user.setRealname(realname);
        user.setSex(new SysDictionary(sex));
        user.setBirthday(CommonUtil.dateParse(birthday));
        user.setQQ(QQ);
        user.setHeadImageFile(headImage);
        user.setDescription(description);
        Result<User> result=service.modify(user,getRequest());

        if (result.isSuccess()){
            return setRequestForwordAttr("信息设置成功","信息设置成功3秒后将跳转到首页","/");
        }else{
             return setMessage("信息设置失败", result.getMessage());
        }

    }




    /*
    * 密码修改页面
    * */
    @RequestMapping(value = "passwordV",method = RequestMethod.GET)
    public  String password(){
        return getPagePath("user/password");
    }



    /*
    * 密码修改
    * */
    @RequestMapping(value = "password",method = RequestMethod.POST)
    public  String password(
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("password") String password
    ){
        Integer id=((User)getSession().getAttribute("user")).getId();
        Result<User> result=service.password(id,oldPassword,password);
        if (result.isSuccess()){

            return setRequestForwordAttr("密码修改成功","信息设置成功3秒后将跳转到首页","/");
        }else{
            setRequestAttr("message",result.getMessage());
            return "forward:/user/password";
        }
    }



}
